package io.gitee.yanbinchen;

import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

/**
 * @author: alex
 * @since : 2025-03-03 19:43
 */
public class SpelUtils {

    public static String getKeyByExpression(Method method, Object[] args, String key) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(key);
        EvaluationContext context = getEvaluationContext(method, args);
        return expression.getValue(context, String.class);
    }

    private static EvaluationContext getEvaluationContext(Method method, Object[] args) {
        DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        String[] parameterNames = nameDiscoverer.getParameterNames(method);
        if (parameterNames != null && args.length == parameterNames.length) {
            for (int i = 0; i < args.length; i++) {
                evaluationContext.setVariable(parameterNames[i], args[i]);
            }
        }
        return evaluationContext;
    }
}
